package com.sicnu.ssj.controller;

import com.sicnu.ssj.pojo.Result;
import com.sicnu.ssj.pojo.User;
import com.sicnu.ssj.service.UserService;
import com.sicnu.ssj.utils.JwtUtil;
import com.sicnu.ssj.utils.Md5Util;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$")String username, String password){
        //查询用户
          User u = userService.findByUsername(username);
          if (u == null) {
              //没有占用
              //注册
              userService.register(username, password);
              return Result.success();
          } else {
              //占用
              return Result.error("用户名已被占用");
          }

    }
    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$")String username, String password){
        //根据用户名查询用户
        User loginUser=userService.findByUsername(username);
        if(loginUser==null){
            return Result.error("用户名不存在");
        }
        //判断密码是否正确 loginuser对象中password是密文
        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())) {
            //登陆成功
            //生成token
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            String token = JwtUtil.genToken(claims);
            return Result.success(token);
        }
        //登陆失败
        return Result.error("密码错误");
    }
    @GetMapping("/userInfo")
    public Result<User> userInfo(@RequestHeader(name = "Authorization") String token){
        //根据用户名查询用户
        Map<String, Object> map = JwtUtil.parseToken(token);
        String username = (String) map.get("username");
        User user = userService.findByUsername(username);
        return Result.success(user);
    }
}
